<template>
	<el-dialog :title="ruleForm.Name+'权限设置'" v-model="isShowDialog" width="800px" :close-on-click-modal="false"
		:close-on-press-escape="false">
		<el-form :model="ruleForm" size="default" label-width="100px" ref="userForm">
			<el-row :gutter="20">
				<el-col :span="12">
					<el-card class="box-card">
						<div slot="header" class="clearfix">
							<span></span>
						</div>
						<div style="height:500px; overflow: auto;">
							<div class="tree-body">
								<Ztree ref="ZtreeRef" />
							</div>
						</div>
					</el-card>
				</el-col>
				<el-col :span="12" v-if="1===2">
					<el-card class="box-card">
						<div slot="header" class="clearfix">
							<span>权限细节</span>
						</div>
						<div style="height:500px; overflow: auto;">
							<div v-if="selectedId!=='' && selectedId!=='0'">
								<el-checkbox :indeterminate="isIndeterminate" v-model="checkAll"
									@change="handleCheckAllChange">全选</el-checkbox>
								<el-checkbox-group v-model="checkedItems" @change="handleCheckedItemsChange">
									<el-checkbox :label="2">读取</el-checkbox>
									<el-checkbox :label="4">创建</el-checkbox>
									<el-checkbox :label="8">修改</el-checkbox>
									<el-checkbox :label="16">删除</el-checkbox>
								</el-checkbox-group>
							</div>
						</div>
					</el-card>
				</el-col>
			</el-row>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="onCancel" size="default">取 消</el-button>
				<el-button type="primary" @click="onSubmit(userForm)" size="default"> 提交 </el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script lang="ts">
	import {
		reactive,
		toRefs,
		onMounted,
		ref,
	} from 'vue';
	import {
		treeAPI,
		treeSaveAPI,
	} from '/@/api/usersroles/index';
	import {
		ElForm,
		ElMessage
	} from 'element-plus';
	import Ztree from "/@/components/ztree/index.vue";
	import commonFunction from '/@/utils/commonFunction';
	export default {
		name: 'UForm',
		components: {
			Ztree
		},
		setup() {
			const {
				getZTree,
			} = commonFunction();
			type FormInstance = InstanceType < typeof ElForm > ;
			const ZtreeRef = ref();
			const readRef = ref();
			const addRef = ref();
			const updateRef = ref();
			const delRef = ref();
			const userForm = ref < FormInstance > ();
			const state = reactive({
				isShowDialog: false,
				ruleForm: {
					ID: '0',
					Name: '',
					Description: '',
				},
				treedata: {},
				selectedId: '',
				tree: [],
				checkAll: false,
				isIndeterminate: true,
				Items: [2, 4, 8, 16],
				checkedItems: []
			});
			// 打开弹窗
			const openDialog = (model: Object, callback: Function) => {
				state.ruleForm = model;
				state.isShowDialog = true;
				TreeInit(true);
			};
			// 关闭弹窗
			const closeDialog = () => {
				state.isShowDialog = false;
			};
			// 取消
			const onCancel = () => {
				closeDialog();
			};
			// 保存
			const onSubmit = (formEl: FormInstance | undefined) => {
				if (!formEl) return
				let zTree = ZtreeRef.value.getTreeObj();
				let nodes = zTree.getCheckedNodes(true);
				let ids = nodes.map(function(item) {
					return item.id ;
				});
				let datalist = ids.join(',')
				//console.log(datalist);
				let ID = state.ruleForm.ID;
		 
				treeSaveAPI({
					datalist,
					ID
				}).then(async (response) => {
					//console.log(response);
					if (response['code'] === 0) {
						if (state.callback) {
							state.callback();
						}
						ElMessage.success(`${response.message}`);
						closeDialog();
					}
				});

			};

			// 页面加载时
			onMounted(() => {


			});

			const TreeInit = (expandAll: boolean) => {
				let ID = state.ruleForm.ID;
				//console.log(state.ruleForm);
				treeAPI({
					ID
				}).then(async (response) => {

					if (response.code === 0) {
						//	console.log(response);
						state.treedata = {}
						state.tree = response.result;
						for (let i = 0; i < response.result.length; i++) {
							state.treedata[response.result[i]['ID']] = response.result[i]['Value'] === null ?
								0 : response.result[i]['Value'];
						}
						 
						ZtreeRef.value.loadTree(state.ruleForm.Name + '权限', getZTree(response.result, '0'),
							setting);
						if (expandAll) {
							var zTree = ZtreeRef.value.getTreeObj();
							zTree.expandAll(true);
						}
					}

				});
			};
			const childCount = (parentId) => {
				let count = 0;
				for (let i = 0; i < state.tree.length; i++) {
					if (state.tree[i]['ParentID'].toString() === parentId.toString()) {
						count++;
					}
				}
				return count;
			}
			const setting = {
				check: {
					enable: true
				},
				edit: {
					enable: true,
					showRemoveBtn: false,
					showRenameBtn: false
				},
				data: {
					simpleData: {
						enable: true,
						idKey: "id",
						pIdKey: "parent",
					}
				},
				callback: {
					onClick: function(event, treeId, treeNode) {
						//console.log(event);
						state.selectedId = "";
						if (treeNode.checked && treeNode.id !== '0' && childCount(treeNode.id) === 0) {
							state.selectedId = treeNode.id;
							loadData();
						}
					},
					onDrag: function(event, treeId, treeNode) {
						//
					},
					onRename: function(event, treeId, treeNode, isCancel) {

					},
					onDrop: function(event, treeId, treeNodes, targetNode, moveType, isCopy) {

					},
					onCheck: function(event, treeId, treeNode) {
						state.selectedId = "";
						if (treeNode.checked && treeNode.id !== '0' && childCount(treeNode.id) === 0) {
							state.selectedId = treeNode.id;
							loadData();
						}
					}
				}
			};
			const loadData = () => {
				let val = 0;
				let checkedItems = [];

				for (let i = 1; i < 5; i++) {
					if ((state.treedata[state.selectedId] & Math.pow(2, i)) > 0) {
						val ^= Math.pow(2, i);
						checkedItems.push(Math.pow(2, i));
					}
				}
				state.checkedItems = checkedItems;
				state.treedata[state.selectedId] = val;
				handleCheckedItemsChange(checkedItems);
			}
			const handleCheckAllChange = (val) => {
				state.checkedItems = val ? state.Items : [];
				state.isIndeterminate = false;
				changeData();
			}
			const handleCheckedItemsChange = (value) => {
				let checkedCount = value.length;
				state.checkAll = checkedCount === state.Items.length;
				state.isIndeterminate = checkedCount > 0 && checkedCount < state.Items.length;
				state.checkedItems = value;
				changeData();
			}
			const changeData = () => {
				let val = 0;
				for (let i = 0; i < state.checkedItems.length; i++) {
					let v = state.checkedItems[i];
					val ^= v;
				}
				state.treedata[state.selectedId] = val;

			}
			return {
				userForm,
				openDialog,
				closeDialog,
				onCancel,
				onSubmit,
				...toRefs(state),
				ZtreeRef,
				readRef,
				addRef,
				updateRef,
				delRef,
				handleCheckAllChange,
				handleCheckedItemsChange
			};
		},
	};
</script>

<style scoped lang="scss">
	.tree-body {
		background-color: #fff;
		padding: 8px 10px;
	}
</style>
